package io.renren.authen.controller;

import io.renren.authen.common.Constant;
import io.renren.common.utils.R;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.service.SysUserTokenService;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;

@Controller
@RequestMapping("/wechat")
public class WechatController {
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    SysUserTokenService sysUserTokenService;

    @RequestMapping("/authorize")
    public String authorize( HttpServletRequest request,@RequestParam("returnUrl")String returnUrl){

//       String url1 = request.getScheme() +"://" + request.getServerName()
//                + ":" +request.getContextPath()+"/"+request.getServerPort()
//                + request.getServletPath();


      String url= returnUrl+"/wechat/userInfo";

        String redirectUrl=wxMpService.oauth2buildAuthorizationUrl(url,WxConsts.OAUTH2_SCOPE_USER_INFO, URLEncoder.encode(returnUrl));
        return "redirect:"+redirectUrl;
    }
    @RequestMapping("/userInfo")
    public String  userInfo(@RequestParam("code")String code,
                         @RequestParam("state")String returnUrl){
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken=new WxMpOAuth2AccessToken();
        try{
            wxMpOAuth2AccessToken=wxMpService.oauth2getAccessToken(code);

        }catch (WxErrorException e){
            System.out.println("网页授权失败");
            return "redirect:" + returnUrl+"/wechat/authorize";
        }
        //验证OpenId
        String openId=wxMpOAuth2AccessToken.getOpenId();
        SysUserEntity sysUserEntity=sysUserService.queryByUserOpenId(openId);
        System.out.println("openId:"+openId);
        if(openId==null){
            return "redirect:" + returnUrl+"/wechat/authorize?returnUrl="+returnUrl;
        }
        R r=null;
        if(sysUserEntity!=null) {
            //生成token，并保存到数据库
//            StudentInfo studentInfo=stuInfoService.GetStuInfo(sysUserEntity.getUsername());
//            TeacherInfoEntity teacherInfo=teacherInfoService.getTeacherInfo(sysUserEntity.getUsername());
             r=sysUserTokenService.createToken(sysUserEntity.getUserId());
//            map.put("token",r.get("token"));
        }else {
            sysUserEntity=new SysUserEntity();
            sysUserEntity.setUsername(openId);
            sysUserEntity.setOpenId(openId);
            sysUserEntity.setPassword("123456");
            sysUserEntity.setStatus(1);
            sysUserService.register(sysUserEntity);
            sysUserEntity=sysUserService.queryByUserName(sysUserEntity.getUsername());
            r=sysUserTokenService.createToken(sysUserEntity.getUserId());
        }
            returnUrl=Constant.wechatlogin;

        return "redirect:" + returnUrl + "?token=" + r.get("token");

    }
}
